﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Fuse8.DomainFramework.Practices.SystemFacade
{
	public static class TreeNode
	{
		public static TreeNode<TKey, TValue> BuildTree<TKey, TValue>(IEnumerable<Tuple<TKey, TKey, TValue>> items, TKey rootKey)
		{
			var nodes = items.Select(x=>new{Parent=x.Item2, Node=new TreeNode<TKey,TValue>{Key = x.Item1, Value = x.Item3}}).ToArray();
			foreach (var node in nodes)
			{
				node.Node.Children.AddRange(nodes.Where(x=>x.Parent.Equals(node.Node.Key)).Select(x=>x.Node));
			}
			return nodes.Single(x => x.Node.Key.Equals(rootKey)).Node;
		}
	}

	public class TreeNode<TKey, TValue>
	{
		public TKey Key;
		public TValue Value;
		public readonly List<TreeNode<TKey, TValue>> Children = new List<TreeNode<TKey, TValue>>();

		public IEnumerable<TreeNode<TKey, TValue>> SelfAndDescendants()
		{
			return (new[] {this}).Union(Children.SelectMany(c => c.SelfAndDescendants()));
		}
	}
}